package com.yxh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yxh.base.PageEntity;
import com.yxh.common.other.Const;
import com.yxh.dao.DeptMapper;
import com.yxh.dao.UserMapper;
import com.yxh.exception.UnitException;
import com.yxh.exception.UserException;
import com.yxh.pojo.*;
import com.yxh.pojo.tree.BaseTreeGrid;
import com.yxh.pojo.vo.UserListVO;
import com.yxh.pojo.vo.UserRestPasswordVO;
import com.yxh.service.GroupService;
import com.yxh.service.UserService;
import com.yxh.util.MD5Util;
import com.yxh.util.SnowflakeIdWorker;
import com.yxh.util.StringUtil;
import com.yxh.util.TreeUtil;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.yxh.util.APIErrorCode.*;

/**
 * Created by 32988 on 2018/5/31.
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GroupService groupService;

    @Autowired
    private DeptMapper deptMapper;

    /**
     * @param user
     */
    public void register(User user) {
        Dept dept=new Dept();
        dept.setFatherId(user.getDept());
      /*  List<Dept> d=deptMapper.selectByDept(dept);
        if(d.size()!=0) throw new UserException(INTERNAL_EXECT_DEPT_ERROR);
        */this.checkValid(user.getUsername(), Const.USERNAME);
        this.checkValid(user.getAccount(), Const.ACCOUNT);
        user.setId(SnowflakeIdWorker.creatId());
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int count = userMapper.insert(user);
        if (count == 0) {
            throw new UserException(REGISTER_ERROR);
        }
    }

    /**
     * @param userRestPasswordVO
     */
    public void resetPassword(UserRestPasswordVO userRestPasswordVO) {
        User user = userMapper.selecyByPassword(MD5Util.MD5EncodeUtf8(userRestPasswordVO.getPasswordOld()), userRestPasswordVO.getUserId());
        if (user == null) {
            throw new UserException(NEWPASSWORD_ERROR);
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(userRestPasswordVO.getPasswordNew()));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount == 0) {
            throw new UserException(NEW_PASSWORD_ERROR);
        }
    }

    public Boolean checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            if (Const.USERNAME.equals(type)) {
                int count = userMapper.checkUsername(str);
                if (count > 0) {
                    throw new UserException(USER_EXIST);
                }
            }
            if (Const.ACCOUNT.equals(type)) {
                int count = userMapper.checkAccount(str);
                if (count > 0) {
                    throw new UserException(ACCOUNT_EXIST);
                }
            }
        } else {
            throw new UserException(PARAMS_INVALID);
        }
        return true;
    }

    public PageInfo getInformation(User user, Integer limit, Integer offset) {
        try {
            PageHelper.startPage(limit, offset);
            List<User> userList = userMapper.selectByUser(user);
            List<UserListVO> userListVOList = new ArrayList<UserListVO>();
            Group group = new Group();
            for (User users : userList) {
                UserListVO userListVO = new UserListVO();
                BeanUtilsBean.getInstance().copyProperties(userListVO, users);
                String[] roles = users.getRole().split(",");
                String valueStr = "";
                for (String role : roles) {
                    group.setId(role);
                    PageInfo pageInfo = groupService.getInformation(group, 1, 10000);
                    List<Group> groups = pageInfo.getList();
                    /*for (int i = 0; i < groups.size(); i++) {
                        valueStr = (i == groups.size() - 1) ?groups.get(i).getName()+ valueStr   : valueStr + groups.get(i).getName() + ",";
                    }*/
                    if (groups.size() > 0) {
                        valueStr = groups.get(0).getName() + "," + valueStr;
                    }
                }
                if (StringUtil.isNotEmpty(valueStr)) {
                    valueStr = valueStr.substring(0, valueStr.length() - 1);
                }
                Dept dept = deptMapper.selectByPrimaryKey(users.getDept());

                if (dept != null) {
                    userListVO.setDeptName(dept.getDeptName());
                }
                userListVO.setRoleNames(valueStr);
                userListVOList.add(userListVO);
            }
            PageInfo pageInfo = new PageInfo(userList);
            pageInfo.setList(userListVOList);
            return pageInfo;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public PageInfo getUserInfo(String userInfo, Integer limit, Integer offset) {
        PageHelper.startPage(limit, offset);
        List<UserListVO> userListVO = userMapper.selectUserByMoreData(userInfo);
        Group group = new Group();
        for (UserListVO userVO : userListVO) {
            String[] roles = userVO.getRole().split(",");
            String valueStr = "";
            for (String role : roles) {
                group.setId(role);
                PageInfo pageInfo = groupService.getInformation(group, 1, 10000);
                List<Group> groups = pageInfo.getList();
                if (groups.size() > 0) {
                    valueStr = groups.get(0).getName() + "," + valueStr;
                }
            }
            if (StringUtil.isNotEmpty(valueStr)) {
                valueStr = valueStr.substring(0, valueStr.length() - 1);
            }

            userVO.setRoleNames(valueStr);
        }
        PageInfo pageInfo = new PageInfo(userListVO);
        return pageInfo;
    }
    @Override
    public List<User> getInformation(String deptId) {


        return userMapper.selectByDept(deptId);
    }

    @Override
    public List<BaseTreeGrid> getList(FlowShip flowShip) {
        List<BaseTreeGrid> list=null;
      /*  if(flowShip.getFlowNodeValue()!=null)
            list=userMapper.selectNewlist(flowShip);
        else*/
        list=userMapper.selectlist();
        TreeUtil tree = new TreeUtil();
        List<BaseTreeGrid> treeGrid = tree.transListTree(list);
        return treeGrid;
    }

    @Override
    public List<Map<String, Object>> selectCheckedList(FlowShip flowShip) {
        return userMapper.selectCheckedList(flowShip);
    }

    public User get(String id) {
        UserKey userKey = new UserKey();
        userKey.setId(id);
        User user = userMapper.selectByPrimaryKey(userKey);
        if (user == null) {
            throw new UserException(USER_NOTEXIST);
        }
        return null;
    }

    public int delete(String id) {
        if (!StringUtil.isEmpty(id)) {
            String[] arr = id.split(",");
            int count = userMapper.deleteByIds(arr);
            if (count == 0) {
                throw new UserException(PARAMS_INVALID);
            }
        }
        return 0;
    }

    public int update(User user) {
        int count = userMapper.updateByPrimaryKeySelective(user);
        return count;
    }

    public int save(User record) {
        return 0;
    }

    public void batchDelete(List<User> records) {

    }

    public User get(User record) {
        return null;
    }

    public List<User> getList(User record) {
        return null;
    }

    public List<User> getAllList(User record) {
        return null;
    }

    public List<User> getListPage(PageEntity<User> record) {
        return null;
    }
}
